package org.lemon.cla.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.lemon.cla.pojo.ClubMember;
import org.lemon.cla.pojo.User; // 导入 User 实体
import org.lemon.cla.mapper.ClubMemberMapper;
import org.lemon.cla.service.IClubMemberService;
import org.lemon.cla.service.IUserService; // 导入 IUserService
import org.lemon.cla.dto.request.ClubMemberSearchRequest;
import org.lemon.cla.enums.ClubMemberRoleEnum;
import org.lemon.cla.enums.ClubMemberStatusEnum;
import org.lemon.cla.vo.ClubMemberVo; // 导入 ClubMemberVo
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional; // 导入 Optional

@Service
public class ClubMemberServiceImpl extends ServiceImpl<ClubMemberMapper, ClubMember> implements IClubMemberService {

    @Autowired
    private IUserService userService; // 注入 IUserService 用于检查用户逻辑删除状态

    // 辅助方法：处理 ClubMemberVo 中的成员用户信息
    private ClubMemberVo processMemberUserInfo(ClubMemberVo memberVo) {
        if (memberVo == null) {
            return null;
        }
        // 如果用户ID为null（例如ON DELETE SET NULL），或者用户被逻辑删除
        if (memberVo.getUserId() == null || (memberVo.getUserIsDeleted() != null && memberVo.getUserIsDeleted())) {
            memberVo.setUsername("未知用户");
            memberVo.setAvatarUrl(null);
            memberVo.setRealName("未知");
            memberVo.setPhone(null);
            memberVo.setEmail(null);
            memberVo.setUserRole(null); // 或者设置为一个默认的未知角色枚举
        }
        return memberVo;
    }

    // 辅助方法：处理分页结果中的成员用户信息
    private IPage<ClubMemberVo> processMemberUserInfoForPage(IPage<ClubMemberVo> page) {
        if (page != null && page.getRecords() != null) {
            page.getRecords().forEach(this::processMemberUserInfo);
        }
        return page;
    }


    @Override
    public boolean isMemberExists(Long userId, Long clubId) {
        QueryWrapper<ClubMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("club_id", clubId);
        return baseMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public boolean updateMemberRole(Long memberId, ClubMemberRoleEnum newRole) {
        ClubMember member = new ClubMember();
        member.setMemberId(memberId);
        member.setRole(newRole);
        return baseMapper.updateById(member) > 0;
    }

    @Override
    public boolean updateMemberStatus(Long memberId, ClubMemberStatusEnum newStatus) {
        ClubMember member = new ClubMember();
        member.setMemberId(memberId);
        member.setStatus(newStatus);
        return baseMapper.updateById(member) > 0;
    }

    @Override
    public boolean withdrawFromClub(Long userId, Long clubId) {
        QueryWrapper<ClubMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("club_id", clubId);
        // 删除匹配的成员关系
        return baseMapper.delete(queryWrapper) > 0;
    }

    @Override
    public ClubMemberVo getClubMemberVoById(Long memberId) {
        ClubMemberVo memberVo = baseMapper.selectClubMemberVoById(memberId);
        return processMemberUserInfo(memberVo); // 处理单个 ClubMemberVo
    }

    @Override
    public IPage<ClubMemberVo> getAllClubMembersVo(Page<ClubMemberVo> page) {
        IPage<ClubMemberVo> memberPage = baseMapper.selectClubMemberVoPage(page);
        return processMemberUserInfoForPage(memberPage); // 处理分页结果
    }

    @Override
    public IPage<ClubMemberVo> searchClubMembersByConditions(Page<ClubMemberVo> page, ClubMemberSearchRequest request) {
        IPage<ClubMemberVo> resultPage = baseMapper.selectClubMemberVoByMultiConditions(page, request);
        return processMemberUserInfoForPage(resultPage); // 处理分页结果
    }
}